package com.tanhua.app.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.model.mongo.UserLike;
import com.itheima.model.mongo.Visitors;
import com.itheima.model.pojo.UserInfo;
import com.itheima.model.vo.FriendsVo;
import com.itheima.model.vo.PageResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class VisitorsService {

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    
    @DubboReference
    private UserLikeApi userLikeApi;
    
    // 分页查看随看过我
    public PageResult<FriendsVo> findPage(Integer page, Integer pagesize, String nickname) {

        // 获取当前用户id
        Long userId = UserHolder.getUserId();

        // 根据用户id，查询visitors信息
        List<Visitors> visitors = visitorsApi.queryPageByVisitorUserId(userId);

        if (CollUtil.isEmpty(visitors)) {
            return null;
        }
        
        // 抽取用户id
        List<Long> userIds = visitors.stream().map(Visitors::getUserId).collect(Collectors.toList());
        
        // 根据用户id列表，获取用户的喜欢列表
        Map<Long, UserLike> map = userLikeApi.findUserIdAndLikeIds(userId, userIds)
                .stream().collect(Collectors.toMap(UserLike::getLikeUserId, Function.identity()));

        // 根据用户id列表，查询用户详情信息
        Page<UserInfo> pageInfo = userInfoApi.findPage(userIds, page, pagesize, nickname);
        List<UserInfo> userInfos = pageInfo.getRecords();

        // 封装数据
        List<FriendsVo> list = new ArrayList<>();

        for (UserInfo userInfo : userInfos) {

            FriendsVo vo = FriendsVo.init(userInfo, map.get(userInfo.getId()) != null && map.get(userInfo.getId()).getIsLike());

            list.add(vo);
        }

        return new PageResult<>(page, pagesize, Integer.parseInt(Long.toString(pageInfo.getTotal())), list);

    }
}
